<?php
namespace Yousheng\DatabaseToolbox\Console;
use Illuminate\Support\Facades\DB;

trait TraitColumns
{
    private static $clumns;
    private static $foreignKeys;
    private static $primaryKey;

    private static $tables;

    public function getTables(){
        if(!static::$tables){
            static::$tables = app('db.schema')->getTables();
        }
        return static::$tables;
    }

    public function initColumns($tables)
    {
        return collect(array_flip($tables))->map(function ($key,$table)  {
            $schema=app('db.schema');
            $_columns = collect($schema->getColumns($table))->map(fn ($column) => new ColumnDefinition([
                'name' => $column['name'],
                'type' => $column['type_name'],
                'full_type_definition' => $column['type'],
                'nullable' => $column['nullable'],
                'default' => is_null($column['default']) ? null : new Expression(Str::wrap($column['default'], '(', ')')),
                'autoIncrement' => $column['auto_increment'],
                'collation' => $column['collation'],
                'comment' => $column['comment'],
                'virtualAs' => ! is_null($column['generation']) && $column['generation']['type'] === 'virtual'
                    ? $column['generation']['expression'] : null,
                'storedAs' => ! is_null($column['generation']) && $column['generation']['type'] === 'stored'
                    ? $column['generation']['expression'] : null,
            ]))->all();

            [$primary, $indexes] = collect($schema->getIndexes($table))->map(fn ($index) => new IndexDefinition([
                'name' => match (true) {
                    $index['primary'] => 'primary',
                    $index['unique'] => 'unique',
                    default => 'index',
                },
                'index' => $index['name'],
                'columns' => $index['columns'],
            ]))->partition(fn ($index) => $index->name === 'primary');

            $indexes = $indexes->all();
            $_primaryKey = $primary->first();


            $_foreignKeys = collect($schema->getForeignKeys($table))->map(fn ($foreignKey) => new ForeignKeyDefinition([
                'columns' => $foreignKey['columns'],
                'on' => new Expression($foreignKey['foreign_table']),
                'references' => $foreignKey['foreign_columns'],
                'onUpdate' => $foreignKey['on_update'],
                'onDelete' => $foreignKey['on_delete'],
            ]))->all();
            return [
                'foreign' => $_foreignKeys,
                'primary' => $_primaryKey,
                'columns' => $_columns
            ];
        })->all();
    }





}